package com.dream.xiaobo.controller;

import com.dream.xiaobo.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 父类Servlet
 * @author xiaobo
 * @date 2021/8/27 - 7:47
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取到访问的方法参数
        String methodStr = req.getParameter(Constants.TAG);

        //校验、如果没有参数和参数为空时直接跳转到首页
        if (null == methodStr || methodStr.equals("")) {
            methodStr = Constants.INDEX;
        }

        //获取到当前类
        Class clazz = this.getClass();

        try {

            //反射拿到与参数类型一致的方法
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //执行拿到的方法
            Object result = method.invoke(this, req, resp);

            //校验拿到的方法
            if(null != result){

                //类型转换
                String str = (String) result;

                //校验、以forword：开头
                if(str.startsWith(Constants.FOR_WARD)){

                    //截取字符串拿到访问路径
                    String path = str.substring(str.indexOf(Constants.FLAG) + 1);
                    //转发
                    req.getRequestDispatcher(path).forward(req,resp);
                //以redirect：开头
                }else if(str.startsWith(Constants.REDIRECT)){
                    //截取字符串拿到访问路径
                    String path = str.substring(str.indexOf(Constants.FLAG) + 1);
                    //重定向
                    resp.sendRedirect(path);
                }else{
                    //字符串返回
                    resp.getWriter().println(str);
                }
            }
        //异常处理
        } catch (Exception e) {
            e.printStackTrace();
            req.getSession().setAttribute("msg","程序异常！！请稍后重试");
            resp.sendRedirect("/message.jsp");
        }
    }

    /**
     * 首页
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String index(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {

        //跳转到首页
        return Constants.FOR_WARD +"/index.jsp";
    }
}
